package com.example.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

public class AuthorizationFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获得请求
        ServerHttpRequest request = exchange.getRequest();

        //2、获取请求头
        HttpHeaders headers = request.getHeaders();
        List<String> authorization = headers.get("authorization");

        //3、如果不为空且有元素且等于admin
        if (authorization != null && authorization.size() != 0 && authorization.get(0).equals("admin")) {
            //满足需求则放行
            return chain.filter(exchange);
        }

        //4、设置响应状态码--401，这里的常量底层就是401，在restFul中401表示未登录
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);

        //5、结束处理
        Mono<Void> voidMono = exchange.getResponse().setComplete();
        return voidMono;
    }
}